package com.example.springmvc_demo2.controller;

import com.example.springmvc_demo2.entity.User;
import com.example.springmvc_demo2.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class AuthController {

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String loginPage(Model model, @RequestParam(value = "error", required = false) String error,
                            @RequestParam(value = "logout", required = false) String logout) {
        if (error != null) {
            model.addAttribute("loginError", "用户名/手机号/邮箱或密码无效。");
        }
        if (logout != null) {
            model.addAttribute("registrationSuccess", "您已成功注销。"); // Reusing for logout message
        }
        model.addAttribute("user", new User()); // Still need to provide a user object for the form
        return "login";
    }

    @GetMapping("/register")
    public String registerPage(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @PostMapping("/register")
    public String register(User user, Model model) {
        // Basic validation for password strength (e.g., length, character types)
        if (user.getPassword() == null || user.getPassword().length() < 6 ||
            !user.getPassword().matches(".*[a-zA-Z].*") || // Contains at least one letter
            !user.getPassword().matches(".*[0-9].*") || // Contains at least one digit
            !user.getPassword().matches(".*[^a-zA-Z0-9].*")) { // Contains at least one special character
            model.addAttribute("registrationError", "密码必须包含英文字母、数字和特殊字符，且长度至少为6位。");
            return "register";
        }

        if (userService.registerUser(user)) {
            model.addAttribute("registrationSuccess", "注册成功！请登录。");
            return "login";
        } else {
            model.addAttribute("registrationError", "用户名、手机号或邮箱已存在。");
            return "register";
        }
    }

    @GetMapping("/password_reset")
    public String passwordResetPage() {
        return "password_reset";
    }

    @PostMapping("/password_reset")
    public String resetPassword(@RequestParam String username, @RequestParam String newPassword, @RequestParam String confirmPassword, Model model) {
        if (!newPassword.equals(confirmPassword)) {
            model.addAttribute("resetError", "两次输入的密码不一致。");
            return "password_reset";
        }
        // Basic validation for new password strength
        if (newPassword.length() < 6 ||
            !newPassword.matches(".*[a-zA-Z].*") ||
            !newPassword.matches(".*[0-9].*") ||
            !newPassword.matches(".*[^a-zA-Z0-9].*")) {
            model.addAttribute("resetError", "新密码必须包含英文字母、数字和特殊字符，且长度至少为6位。");
            return "password_reset";
        }

        if (userService.updatePassword(username, newPassword)) {
            model.addAttribute("resetSuccess", "密码修改成功，请重新登录。");
            return "login";
        } else {
            model.addAttribute("resetError", "修改密码失败，用户可能不存在或新旧密码相同。");
            return "password_reset";
        }
    }

    @GetMapping("/index")
    public String indexPage(Model model) {
        // Get the authenticated user's principal from Spring Security context
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        String username;
        if (principal instanceof UserDetails) {
            username = ((UserDetails) principal).getUsername();
        } else {
            username = principal.toString(); // Fallback for non-UserDetails principals
        }

        model.addAttribute("username", username);
        return "index";
    }

    @GetMapping("/error")
    public String errorPage() {
        return "error";
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        return "redirect:/login?logout";
    }
} 